import React, { createContext, useReducer, useEffect, useState } from "react";
import { Alert } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import query from "../../api/query";

const SampleVillageContext = createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "fetch_init":
      return action.payload;
    case "add_sampleVillage":
      return [...state, action.payload];
    case "edit_sampleVillage":
      return state.map((item) => {
        return item._id === action.payload._id ? action.payload : item;
      });
    case "delete_sampleVillage":
      return state.filter((item) => item._id !== action.payload);
    case "set_status":
      return action.payload;
  }
};

export const SampleVillageProvider = ({ children }) => {
  const [villageLists, dispatch] = useReducer(dataReducer, []);
  const [isVillageLoading, setIsVillageLoading] = useState(false);
  const [isVillageError, setIsVillageError] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      setIsVillageLoading(true);
      setIsVillageError(false);

      try {
        const token = await AsyncStorage.getItem("token");
        const result = await query.get("/sampleVillage", {
          headers: { Authorization: token },
        });
        dispatch({ type: "fetch_init", payload: result.data.data });
      } catch (err) {
        setIsVillageError(true);

        console.log("初始化样本村出错", err);
      }
      setIsVillageLoading(false);
    };
    fetchData();
  }, []);

  const addSampleVillage = async (sampleVillage, callback) => {
    try {
      setIsVillageLoading(true);
      const token = await AsyncStorage.getItem("token");
      const result = await query.post("/sampleVillage", sampleVillage, {
        headers: { Authorization: token },
      });
      dispatch({ type: "add_sampleVillage", payload: result.data.data });
      Alert.alert("", "添加样本村成功", [
        {
          text: "确定",
          onPress: () => callback(),
        },
      ]);
    } catch (err) {
      console.log("添加样本村失败", err);
      Alert.alert("", "添加样本村失败");
    }
    setIsVillageLoading(false);
  };

  const editSampleVillage = async (village, callback) => {
    try {
      setIsVillageLoading(true);
      const token = await AsyncStorage.getItem("token");
      const result = await query.patch(
        "/sampleVillage/" + village._id,
        village,
        {
          headers: { Authorization: token },
        }
      );
      dispatch({ type: "edit_sampleVillage", payload: result.data.data });
      Alert.alert("", "样本村修改成功", [
        {
          text: "确定",
          onPress: () => callback(),
        },
      ]);
    } catch (err) {
      console.log("修改样本村失败", err);
      Alert.alert("", "修改样本村失败");
    }
    setIsVillageLoading(false);
  };

  const deleteSampleVillage = async (villageId) => {
    try {
      setIsVillageLoading(true);
      const token = await AsyncStorage.getItem("token");
      await query.delete("/sampleVillage/" + villageId, {
        headers: { Authorization: token },
      });
      dispatch({ type: "delete_sampleVillage", payload: villageId });
      Alert.alert("", "样本村删除成功", [
        {
          text: "确定",
        },
      ]);
    } catch (err) {
      console.log("删除样本村失败", err);
      Alert.alert("", "删除样本村失败");
    }
    setIsVillageLoading(false);
  };

  //传入id数组
  const setStatus = async (idGroup) => {
    try {
      setIsVillageLoading(true);
      const token = await AsyncStorage.getItem("token");
      const result = await query.post("/sampleVillage/publish", idGroup, {
        headers: { Authorization: token },
      });
      dispatch({ type: "set_status", payload: result.data.data });
      Alert.alert("", "样本村发布成功", [
        {
          text: "确定",
        },
      ]);
    } catch (err) {
      console.log("样本村发布失败", err);
      Alert.alert("", "样本村发布失败");
    }
    setIsVillageLoading(false);
  };

  return (
    <SampleVillageContext.Provider
      value={{
        villageLists: villageLists,
        addSampleVillage,
        editSampleVillage,
        deleteSampleVillage,
        setStatus,
        isVillageLoading,
      }}
    >
      {children}
    </SampleVillageContext.Provider>
  );
};

export default SampleVillageContext;
